﻿using System;
using System.Runtime.InteropServices;
using System.Text;

namespace EzyConfigurator
{
    internal class Ini
    {
        /*
        [DllImport("kernel32", CharSet =CharSet.Unicode)]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
        public static string Read(string section, string key, string def, string filePath)
        {
            StringBuilder sb = new StringBuilder(1024);
            GetPrivateProfileString(section, key, def, sb, 1024, filePath);
            return sb.ToString();
        }

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern int WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);
        public static int Write(string section, string key, string value, string filePath)
         {
             return WritePrivateProfileString(section, key, value, filePath);
         }*/






        //ini文件

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);

        [DllImport("kernel32.dll")]
        private static extern long WritePrivateProfileString(string section, byte[] key, byte[] val, string filePath);

        /// <summary>
        /// 指定节点 指定键写入值
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="Key">键</param>
        /// <param name="Value">值</param>
        /// <returns></returns>
        public static bool Write(string Section, string Key, string Value, string filename)
        {
            try
            {
                WritePrivateProfileString(Section, Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(Value), filename);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string Read(string Section, string Key, string def, string FileName)
        {
            try
            {
                byte[] Buffer = new byte[10240];
                int bufLen = GetPrivateProfileString(Section, Key, def, Buffer, Buffer.GetUpperBound(0), FileName);
                string s = Encoding.UTF8.GetString(Buffer, 0, bufLen);
                return s;
            }
            catch
            {
                return string.Empty;
            }
        }

    }
}
